﻿var Store = (function () {
    var setOfCats = [];
    var i = 0;
    var j = 0;

    function initStore(setOfCategories) {
        setOfCats = setOfCategories;
        $('body').append('<div id="store-wrapper"></div>');
        buildCategories();
        createCashRegister();
        sellProduct(500);
    }

    function buildCategories() {
        var categoryWrapper = $('<div id="cat-wrapper"></div>');

        // interating over all categories int the DB
        for (i = 0; i < setOfCats.length; i++) {

            var currentCategory = $('<div class="category"></div>');

            // title of the category
            currentCategory.append('<h3>' + setOfCats[i].categoryName + '</h3>');
            
            // table creation
            var currentTable = $('<table></table>');

            // table head creation
            currentCategory.append(currentTable);
            var currentTableHead = $('<thead></thead>');
            var currentTableHeadRow = $('<tr></tr>');
            console.log(currentTableHeadRow);

            // product header cells generation
            for (var prop in setOfCats[i].setOfProducts[i]) {
                if (setOfCats[i].setOfProducts[i].hasOwnProperty(prop)) {
                    if (prop) {
                        currentTableHeadRow.append('<th>' + prop + '</th>');
                    }
                }
            }

            currentTable.append(currentTableHead.append(currentTableHeadRow));

            // Product generation
            for (j = 0; j < setOfCats[i].setOfProducts.length; j++) {
                var currentProductWrapper = $('<tr class="product"></tr>');
                var currentProduct = setOfCats[i].setOfProducts[j];
                currentProductWrapper.append(currentProduct.toHTML());
                currentTable.append(currentProductWrapper);
            }

            categoryWrapper.append(currentCategory);
        }

        $('#store-wrapper').append(categoryWrapper);
    }

    // cash register generation and visualisation
    function createCashRegister() {
        this.reg = new CashRegister();
        reg.initialise(0);
        var cashRegister = $('<div id="cash-register"> \
            <p>Balance in leva: ' + reg.balance + ' lv. </p> \
            <p>Balance in USD: ' + reg.getCashInUSD() + ' eruo </p> \
            <p>Balance in Euro: ' + reg.getCashInEuro() + ' $ </p> \
            </div>');
        $('#cash').append(cashRegister);
    }

    // TODO: Do we need this ?
    function sellProduct(product) {
        reg.add(product.price);
    }

    // needed methods returns
    return {
        initStore: initStore
    }
})();